open BUFF,"<merge_expr_sortedage_commonsamples" or die "no file exists merge_expr\n";
open(WRBUFF,">merge_expr_sortedage_commonsamples_out");
open(BUFF1,"PARSED_CLINICALDATA_MARTINGALE");
$line = <BUFF1>;
while($line = <BUFF1>)
{
	chomp($line);
	$line =~ s/^\t+//g;
	$line =~ s/"//g;
	@clinicalarray = split("\t",$line);
	
	#print "$clinicalarray[0]\t$clinicalarray[@clinicalarray-1]\n";
	$clinicalarray{$clinicalarray[0]} = $clinicalarray[@clinicalarray-1];
}
#read the first line in  expr file for sample names
$line = <BUFF>;
chomp($line);
#create sample array expr
@gene_samples_before = split(/\t/,$line);
for($i=0;$i<@gene_samples_before;$i++)
{
	if(exists($clinicalarray{$gene_samples_before[$i]}))
	{
		#print "sucess\n";
		$gene_samples_before{$gene_samples_before[$i]} = $clinicalarray{$gene_samples_before[$i]}; 				
	}
	else
	{
		$gene_samples_before{$gene_samples_before[$i]} = 0;
	}
	$gene_samples_before_index{$gene_samples_before[$i]} = $i;
}
$num_incr = 0;
#print "@gene_samples_before\n";
foreach $key (sort {$gene_samples_before{$a} <=> $gene_samples_before{$b} }keys %gene_samples_before)
{
	
    	#print "$key\t$gene_samples_before{$key}\n";
	if($gene_samples_before{$key} != 0)
	{
		#print "\t".$gene_samples_before{$key};
		print WRBUFF "\t".$key;	
		
		$main_array_expr[$gene_samples_before_index{$key}] = $num_incr;
		$num_incr++; 
	}
	else
	{
		$main_array_expr[$gene_samples_before_index{$key}] = -1;
	}
	#if($num_incr == 1)
	#{	
	#	print "$key\t$gene_samples_before{$key}\n";
	#}
}
print WRBUFF "\n";

while($line=<BUFF>)
{
	chomp($line);
	@array = ();
	@array = split("\t",$line);
	@main_array_expr1 = ();
	$id = shift(@array);
	print WRBUFF $id."\t";
	$l1 = @array;
	$l2 = @main_array_expr;
	#print "$l1\t$l2\n";
	for($i=0;$i<@array;$i++)
	{
		if($l1 == $l2 && $main_array_expr[$i] != -1)
		{
			$main_array_expr1[$main_array_expr[$i]] = $array[$i];
		}
	}
	$temp = join("\t",@main_array_expr1);
	print WRBUFF $temp."\n";
}
#print "@main_array_expr\n";
